package com.googlecode.pwlodars.piteststat.writer.run;


import java.io.File;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.googlecode.pwlodars.piteststat.config.CommonConfig;
import com.googlecode.pwlodars.piteststat.content.PitestSingleResult;
import com.googlecode.pwlodars.piteststat.database.PitResultDao;
import com.googlecode.pwlodars.piteststat.filesystembridge.FileSystemConnector;
import com.googlecode.pwlodars.piteststat.writer.config.WriterConfig;
import com.googlecode.pwlodars.piteststat.writer.content.PitResultFileInfo;
import com.googlecode.pwlodars.piteststat.writer.content.PitResultsFilesReader;
import com.googlecode.pwlodars.piteststat.writer.content.PitestResultFilesParser;

public class Main {

	
	private final static Logger log=Logger.getLogger(Main.class);
	
	private final FileSystemConnector fileSystemConnector;
	
	private final PitResultsFilesReader pitResultsFilesReader;
	
	private final ParametersResolver parametersResolver;
	
	private final PitestResultFilesParser pitestResultFilesParser;
	
	private PitResultDao pitResultDao;
	
	public Main() {
		ApplicationContext context=new AnnotationConfigApplicationContext(CommonConfig.class,WriterConfig.class);
		parametersResolver = context.getBean(ParametersResolver.class);
		fileSystemConnector = context.getBean(FileSystemConnector.class);
		pitResultsFilesReader=context.getBean(PitResultsFilesReader.class);
		pitestResultFilesParser=context.getBean(PitestResultFilesParser.class);
		pitResultDao=context.getBean(PitResultDao.class);
	}
	
	public static void main(String[] args) {
		new Main().startApplication(args);
	}
	
	public void startApplication(String[] args){
		ConsoleParameters parameters = resolveParams(args);
		List<File> folders = fileSystemConnector.listFolders(parameters.getPathToPitResultFiles());
		List<PitResultFileInfo> parseResultFiles = pitResultsFilesReader.readResultFiles(folders);
		
		for (PitResultFileInfo resultFileContent : parseResultFiles) {
			List<PitestSingleResult> parseResults = pitestResultFilesParser.parseResults(resultFileContent);
			saveResults(parseResults);
		}
		
		
		
	}

	private void saveResults(List<PitestSingleResult> parseResults) {
		for (PitestSingleResult pitestSingleResult : parseResults) {
			log.info("saving result : "+pitestSingleResult);
			pitResultDao.saveResult(pitestSingleResult);
		}
	}

	private ConsoleParameters resolveParams(String[] args) {
		ConsoleParameters parameters = parametersResolver.resolveParameters(args);
		log.info("------------received parameters-------------"); 
		log.info(parameters.toString());
		return parameters;
	}
}
